package com.xm.permission;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.graphics.Path;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 手势控制器 - 负责处理点击和滑动操作
 */
public class GestureController {
    private static final String TAG = "GestureController";
    private static final Handler handler = new Handler(Looper.getMainLooper());
    private static final int GESTURE_TIMEOUT = 3000; // 手势超时时间(毫秒)

    /**
     * 执行点击操作
     */
    public static void performClick(float x, float y, GestureCallback callback) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            if (callback != null) {
                callback.onGestureResult(false, "设备系统版本过低，不支持该操作", "click");
            }
            return;
        }

        AccessibilityService service = AutoStartAccessibilityService.getInstance();
        if (service == null) {
            if (callback != null) {
                callback.onGestureResult(false, "无障碍服务未运行，请开启服务", "click");
            }
            return;
        }

        Log.i(TAG, "执行点击操作：(" + x + ", " + y + ")");

        // 创建点击路径
        Path clickPath = new Path();
        clickPath.moveTo(x, y);

        GestureDescription.StrokeDescription clickStroke = 
                new GestureDescription.StrokeDescription(clickPath, 0, 50);

        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(clickStroke);

        // 超时检测
        final boolean[] callbackReceived = {false};
        
        final Runnable timeoutRunnable = () -> {
            if (!callbackReceived[0] && callback != null) {
                Log.w(TAG, "点击手势回调超时");
                callback.onGestureResult(false, "操作超时未响应", "click");
            }
        };
        
        // 设置超时检测
        handler.postDelayed(timeoutRunnable, GESTURE_TIMEOUT);

        boolean dispatchResult = service.dispatchGesture(gestureBuilder.build(), new AccessibilityService.GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                callbackReceived[0] = true;
                handler.removeCallbacks(timeoutRunnable);
                
                Log.i(TAG, "点击操作完成: (" + x + ", " + y + ")");
                if (callback != null) {
                    handler.post(() -> callback.onGestureResult(true, "点击成功", "click"));
                }
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                callbackReceived[0] = true;
                handler.removeCallbacks(timeoutRunnable);
                
                Log.e(TAG, "点击操作被取消: (" + x + ", " + y + ")");
                if (callback != null) {
                    handler.post(() -> callback.onGestureResult(false, "点击被系统取消", "click"));
                }
            }
        }, null);

        if (!dispatchResult) {
            callbackReceived[0] = true;
            handler.removeCallbacks(timeoutRunnable);
            
            Log.e(TAG, "点击手势分发失败: (" + x + ", " + y + ")");
            if (callback != null) {
                callback.onGestureResult(false, "手势分发失败", "click");
            }
        }
    }

    /**
     * 执行滑动操作
     */
    public static void performSwipe(float x1, float y1, float x2, float y2, GestureCallback callback) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            if (callback != null) {
                callback.onGestureResult(false, "设备系统版本过低，不支持该操作", "swipe");
            }
            return;
        }

        AccessibilityService service = AutoStartAccessibilityService.getInstance();
        if (service == null) {
            if (callback != null) {
                callback.onGestureResult(false, "无障碍服务未运行，请开启服务", "swipe");
            }
            return;
        }

        Log.i(TAG, "执行滑动操作：(" + x1 + ", " + y1 + ") → (" + x2 + ", " + y2 + ")");

        // 创建滑动路径
        Path swipePath = new Path();
        swipePath.moveTo(x1, y1);
        swipePath.lineTo(x2, y2);

        // 增加滑动时间提高成功率
        GestureDescription.StrokeDescription swipeStroke = 
                new GestureDescription.StrokeDescription(swipePath, 0, 500);

        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(swipeStroke);

        // 超时检测
        final boolean[] callbackReceived = {false};
        
        final Runnable timeoutRunnable = () -> {
            if (!callbackReceived[0] && callback != null) {
                Log.w(TAG, "滑动手势回调超时");
                callback.onGestureResult(false, "操作超时未响应", "swipe");
            }
        };
        
        // 设置超时检测
        handler.postDelayed(timeoutRunnable, GESTURE_TIMEOUT);

        boolean dispatchResult = service.dispatchGesture(gestureBuilder.build(), new AccessibilityService.GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                callbackReceived[0] = true;
                handler.removeCallbacks(timeoutRunnable);
                
                Log.i(TAG, "滑动操作完成: (" + x1 + ", " + y1 + ") → (" + x2 + ", " + y2 + ")");
                if (callback != null) {
                    handler.post(() -> callback.onGestureResult(true, "滑动成功", "swipe"));
                }
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                callbackReceived[0] = true;
                handler.removeCallbacks(timeoutRunnable);
                
                Log.e(TAG, "滑动操作被取消: (" + x1 + ", " + y1 + ") → (" + x2 + ", " + y2 + ")");
                if (callback != null) {
                    handler.post(() -> callback.onGestureResult(false, "滑动被系统取消", "swipe"));
                }
            }
        }, null);

        if (!dispatchResult) {
            callbackReceived[0] = true;
            handler.removeCallbacks(timeoutRunnable);
            
            Log.e(TAG, "滑动手势分发失败: (" + x1 + ", " + y1 + ") → (" + x2 + ", " + y2 + ")");
            if (callback != null) {
                callback.onGestureResult(false, "手势分发失败", "swipe");
            }
        }
    }

    /**
     * 手势操作回调接口
     */
    public interface GestureCallback {
        void onGestureResult(boolean success, String message, String operationType);
    }
} 